#include "xSceneManger.h"
#include "threadSafeUpdateCallback.h"
#include <osgDB/WriteFile>
#include <osgDB/ReadFile>
#include <qcomm.h>

xSceneManger::xSceneManger(osg::Group* root)
{
    ptrRoot = root;
}

xSceneManger::~xSceneManger()
{

}

void xSceneManger::loadScene(std::string fileName)
{
    //读取数据
    osg::ref_ptr<osg::Node> node = osgDB::readNodeFile(fileName);

    if(!node)
    {
        return;
    }

    //添加数据
    osg::ref_ptr<osg::Node> parent = ptrRoot->getChild(0);

    if(parent)
    {
        parent->asGroup()->addChild(node);
    }

    //哈希表记录
    m_nodeContainer.insert(fileName, node);

}

void xSceneManger::unloadScene(std::string fileName)
{
    NodeAssocContainerIter iter = m_nodeContainer.find(fileName);

    if(m_nodeContainer.end() == iter)
    {
        return;
    }

    osg::ref_ptr<CThreadSafeUpdateCallback> spChildCallback = dynamic_cast<CThreadSafeUpdateCallback*>(ptrRoot->getUpdateCallback());

    if (spChildCallback != NULL)
    {
        osg::ref_ptr<osg::Node> parent = ptrRoot->getChild(0);

        if(parent)
        {
            spChildCallback->RemoveChild(parent, iter.value());
            m_nodeContainer.erase(iter);
        }
    }
}

void xSceneManger::unloadAll()
{
    int numChild = ptrRoot->getNumChildren();

    if (numChild == 0)
    {
        return;
    }

    for (int i = 0; i < numChild; i++)
    {
        osg::ref_ptr<osg::Group> group = ptrRoot->getChild(i)->asGroup();

        if (group)
        {
            if (group->getName() == "viewerGroup")
            {
                continue;
            }

            osg::ref_ptr<CThreadSafeUpdateCallback> spChildCallback = dynamic_cast<CThreadSafeUpdateCallback*>(ptrRoot->getUpdateCallback());

            if (spChildCallback != NULL)
            {
                int numGroupChild = group->getNumChildren();

                for (int j = 0; j < numGroupChild; j++)
                {
                    osg::ref_ptr<osg::Node> childNode = group->getChild(j);
                    spChildCallback->RemoveChild(group, childNode);
                }
            }
        }
    }

    m_nodeContainer.clear();
}

void xSceneManger::checkScene(std::string fileName)
{
    //哈希表查找
    NodeAssocContainerIter iter = m_nodeContainer.find(fileName);

    if(m_nodeContainer.end() == iter)
    {
        return;
    }

    osg::ref_ptr<osg::Node> node = iter.value();

    if(!node)
    {
        return;
    }

    //改变隐藏状态
    const osg::Node::NodeMask nm = node->getNodeMask();

    if(nm == 0x0)
    {
        node->setNodeMask(1);
    }
    else
    {
        node->setNodeMask(0x0);
    }
}


xSceneManger *xSceneManger::getInstance(osg::Group *root)
{
    static xSceneManger loadManager(root);
    return &loadManager;
}
